<!DOCTYPE html>
<title>Cross origin WebBundle subresource loading</title>
<link rel="help" href="https://github.com/WICG/webpackage/blob/master/explainers/subresource-loading.md" />
<link rel="help" href="https://html.spec.whatwg.org/multipage/#cors-settings-attribute" />
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="../resources/test-helpers.js"></script>

<body>
  <!--
       This wpt should run on an origin different from https://www1.web-platform.test:8444/,
       from where cross-orign WebBundles are served.

       This test uses a cross-origin WebBundle,
       https://www1.web-platform.test:8444/web-bundle/resources/wbn/cors/cross-origin.wbn,
       which is served with an Access-Control-Allow-Origin response header.

       `cross-origin.wbn` includes two subresources:
       a. `resource.cors.json`, which includes an Access-Control-Allow-Origin response header.
       b. `resource.no-cors.json`, which doesn't include an Access-Control-Allow-Origin response header.
  -->
  <script>
    promise_test(async () => {
      const prefix =
        "https://www1.web-platform.test:8444/web-bundle/resources/wbn/cors/";
      const resources = [
        prefix + "resource.cors.js",
        prefix + "resource.no-cors.js",
      ];
      for (const crossorigin_attribute_value of [
        undefined,   // crossorigin attribute is not set
        "anonymous",
        "use-credential",
      ]) {
        const link = await addLinkAndWaitForLoad(
          prefix + "cross-origin.wbn",
          resources,
          crossorigin_attribute_value
        );

        // Can fetch a subresource which has a valid Access-Control-Allow-Origin response header.
        const response = await fetch(prefix + "resource.cors.js");
        assert_true(response.ok);
        const text = await response.text();
        assert_equals(text, "scriptLoaded('resource.cors.js');");

        // Can not fetch a subresource which does NOT have a valid
        // Access-Control-Allow-Origin response header.
        await fetchAndWaitForReject(prefix + "resource.no-cors.js");

        // Both subresource js can be loaded via a <script> element, which doesn't use cors.
        for (const resource of resources) {
          const scriptEvaluted = new Promise((resolve, reject) => {
            window.scriptLoaded = resolve;
          });
          const script = document.createElement("script");
          script.src = resource;
          document.body.appendChild(script);
          await scriptEvaluted;
        }
        link.remove();
      }
    }, "request's mode must be cors. A server should return a valid Access-Control-Allow-Origin header if a bundle is a cross origin bundle.");
  </script>
</body>
